import { ProForm, ProFormCaptcha, ProFormText } from "@ant-design/pro-components";
import {  resetMyPwdVcodeKeyStorage } from "@/utils/storage";
import { vcodeV1ControllerSendMineMobileVcode } from "@/services/auto/vcode";
import { SendMineVcodeType } from "common/utils/data";
import { Card, message } from "antd";
import React from "react";
import { PASSWORD_REGEXP } from "common/utils/regexp";
import { userV1ControllerCreate, userV1ControllerUpdateMinePassword } from "@/services/auto/user";
import {history} from "@umijs/max";
import { openLoginModal } from "@/components/LoginModal";

interface FormData extends API.UserUpdatePasswordDto {
  password2: string;
}

export default function (){
  const [form] = ProForm.useForm<FormData>();

  return <Card>
    <ProForm style={{width: 500}} onFinish={(values)=>{
      const {password2, ...restValues} = values;
      return userV1ControllerUpdateMinePassword({
        ...restValues,
        vcodeKey: resetMyPwdVcodeKeyStorage.get() ?? undefined,
      }).then(()=>{
        message.success('修改密码成功，请重新登录');
        history.push('/home');
        setTimeout(()=>{
          openLoginModal();
        }, 500);
        return true
      }).catch(()=>{
        return false;
      });
    }} form={form} submitter={{
      resetButtonProps: {
        style: {display: 'none'}
      },
    }}>
      <ProFormCaptcha
        fieldProps={{
          maxLength: 6,
        }}
        placeholder={'账号绑定手机收到验证码后，输入6位验证码'}
        captchaTextRender={(timing, count) => {
          if (timing) {
            return `${count} ${'获取验证码'}`;
          }
          return '获取验证码';
        }}
        name="vcode"
        rules={[
          {
            required: true,
            message: '请输入6位验证码',
            min: 6,
            max: 6
          },
        ]}
        onGetCaptcha={async () => {
          const cacheVcodeKey = resetMyPwdVcodeKeyStorage.get();

          const res = await vcodeV1ControllerSendMineMobileVcode({
            vcodeKey: cacheVcodeKey ?? undefined,
            type: SendMineVcodeType.USER_RESET_MY_PWD,
          })

          if(res.vcodeKey === cacheVcodeKey){
            message.success('您的上次验证码还未失效，请直接使用');
          }else{
            resetMyPwdVcodeKeyStorage.set(res.vcodeKey);
            message.success('获取验证码成功！');
          }
        }}
      />
      <ProFormText.Password
        name="password"
        fieldProps={{
          maxLength: 20,
        }}
        placeholder="密码"
        rules={[
          {
            required: true,
            pattern: PASSWORD_REGEXP,
            message: '请填写6-20位密码，至少包含英文、数字、符号其中两种',
          },
        ]}
      />
      <ProFormText.Password
        name="password2"
        placeholder="确认密码"
        rules={[
          (form)=>{
            const password = form.getFieldValue('password');
            return {
              validator: (_, value,)=>{
                if(!value || value !== password){
                  return Promise.reject('请填写确认密码，且与密码一致')
                }
                return Promise.resolve();
              },
            }
          },
        ]}
      />
    </ProForm>
  </Card>
}
